package com.cloud.framework.handler;

import com.cloud.common.constant.Constants;
import com.cloud.common.core.domain.entity.SysUser;
import com.cloud.common.core.domain.model.LoginUser;
import com.cloud.common.core.domain.model.RegisterBody;
import com.cloud.common.core.redis.RedisCache;
import com.cloud.common.exception.ServiceException;
import com.cloud.common.exception.user.UserPasswordNotMatchException;
import com.cloud.common.utils.MessageUtils;
import com.cloud.common.utils.StringUtils;
import com.cloud.framework.manager.AsyncManager;
import com.cloud.framework.manager.factory.AsyncFactory;
import com.cloud.framework.security.context.AuthenticationContextHolder;
import com.cloud.framework.web.service.SysRegisterService;
import com.cloud.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Random;

@Component
public class SmsLoginHanlder extends LoginHanlder implements LoginStrategy {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysRegisterService registerService;

    @Override
    public String getLoginType() {
        return "sms";
    }

    @Override
    public String login(String phone, String password, String code, String uuid) {
        checkCode(phone, code);
        //查询用户
        SysUser sysUser = selectUserByPhone(phone);
        if (Objects.isNull(sysUser)) {
            // 注册用户
            String userName = generateRandomLetters();
            sysUser = new SysUser();
            sysUser.setUserName(userName);
            sysUser.setPhonenumber(phone);
            while (!userService.checkUserNameUnique(sysUser)){
                userName = generateRandomLetters();
                sysUser.setUserName(userName);
            }
            RegisterBody registerBody = new RegisterBody();
            registerBody.setUsername(userName);
            registerBody.setPhonenumber(phone);
            registerBody.setPassword("123456");
            registerBody.setRegisterType("client");
            registerService.register(registerBody);
            sysUser = selectUserByPhone(phone);


        }

        // 用户验证
        Authentication authentication = null;
        try {
            authentication = authenticate(new LoginAuthenticationToken(sysUser.getUserName(), "sms"));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return getToken(loginUser);
    }

    private void checkCode(String phone, String code) {

        if (StringUtils.isBlank(code)) {
            throw new RuntimeException("验证码不能为空");
        }
        if (isSuperAccount(phone)) {
            return;
        }
        // todo 发送验证码
        /*String key = "SMS_CODE_KEY:" + phone;
        redisCache.redisTemplate.setKeySerializer(new StringRedisSerializer());

        if (!redisCache.redisTemplate.hasKey(key)) {
            throw new RuntimeException("验证码不正确");
        }
        Object codeObj = redisCache.redisTemplate.opsForValue().get(key);

        if (codeObj == null) {
            throw new RuntimeException("验证码不正确");
        }
        String saveCode = codeObj.toString();
        if (StringUtils.isBlank(saveCode)) {
            redisCache.redisTemplate.delete(key);
            throw new RuntimeException("验证码不正确");
        }
        if (!StringUtils.equals(saveCode, code)) {
            throw new RuntimeException("验证码不正确");
        }
        redisCache.redisTemplate.delete(key);*/
    }

    private Boolean isSuperAccount(String mobile) {
        List<String> accountList = redisCache.redisTemplate.opsForList().range("SUPER_ACCOUNT:", 0, -1);
        if (accountList != null) {
            for (String s : accountList) {
                if (mobile.contains(s)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static String generateRandomLetters() {
        StringBuilder sb = new StringBuilder();

        // 创建一个包含所有小写字母的数组
        char[] letterArray = "abcdefghijklmnopqrstuvwxyz".toCharArray();

        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int index = random.nextInt(letterArray.length);

            // 将随机选取的字符添加到字符串中
            sb.append(letterArray[index]);
        }

        return sb.toString();
    }
}